package bank_to_bank;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

import bank_access.Kommunikationsmodul;

/**
 * @author pascal
 * 
 * Listens to a specified port and 
 *
 */
public class TransferHandlerSkeleton extends Thread {

    private TransferHandlerImplBase xferHandler;
    private int port;
    private ServerSocket serverSocket;
    private ExecutorService threadPool =
            Executors.newFixedThreadPool(3);
    private Logger logger;

    public TransferHandlerSkeleton(Object xfer, int port) {
        logger = Kommunikationsmodul.getLogger();
        if (xfer instanceof TransferHandlerImplBase) {
            this.xferHandler = (TransferHandlerImplBase) xfer;
        } else {
            throw new IllegalArgumentException("xfer ist nicht vom Typ TransferHandlerImplBase.");
        }
        this.port = port;
    }

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(port);
            logger.info("Lausche auf Port " + port);
            while (true) {
                Socket connectionSocket = serverSocket.accept();
                logger.info("Verbindung aufgenommen zu " + connectionSocket.getInetAddress().getCanonicalHostName());
                threadPool.execute(new TransferHandlerSkeletonTask(xferHandler, connectionSocket));
            }
        } catch (IOException e) {
            logger.severe("IOException " + e);
        }
    }
}
